package com.spice.service.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spice.common.exception.SpiceException;
import com.spice.common.result.Response;
import com.spice.common.result.ResultCodeEnum;
import com.spice.common.util.CheckUtil;
import com.spice.service.util.ShiroUtil;
import com.spice.service.entity.form.UserLoginForm;
import com.spice.service.entity.pojo.User;
import com.spice.service.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * @author yinhaiming
 */
@Api(value = "登录控制器")
@RestController
@RequestMapping("/api/login")
public class LoginController {

    @Autowired
    UserService userService;



    @ApiOperation(value = "获取当前用户信息")
    @PostMapping(value = "/whoIAm", produces = "application/json;charset=UTF-8")
    public Response whoIAm() throws InterruptedException, IOException {
        if (!ShiroUtil.isAuthenticated()) {
            return Response.setResult(ResultCodeEnum.NO_AUTHENTICATION);
        }
        return Response.ok()
                .data("user", userService.getOne(new LambdaQueryWrapper<User>()
                        .eq(User::getUsername,
                                SecurityUtils.getSubject().getPrincipal().toString())))
                .data("sessionId", ShiroUtil.getSessionId());

    }

    @ApiOperation(value = "登录")
    @PostMapping(value = "/toLogin", produces = "application/json;charset=UTF-8")
    public Response usernameLogin(@RequestBody UserLoginForm userLoginForm, HttpServletRequest request) throws IOException {
        //判断必要参数是否齐全
        if (CheckUtil.objectsHasNull(
                userLoginForm.getUsername(),
                userLoginForm.getPassword())
        ) {
            return Response.setResult(ResultCodeEnum.PARAM_ERROR);
        } else {
            try {
                SecurityUtils.getSubject()
                        .login(new UsernamePasswordToken(
                                userLoginForm.getUsername(),
                                userLoginForm.getPassword()));
                return Response.ok()
                        .data("user", userService.getOne(new LambdaQueryWrapper<User>()
                                .eq(User::getUsername, userLoginForm.getUsername())))
                        .data("sessionId", ShiroUtil.getSessionId());
            } catch (AuthenticationException e) {
                e.printStackTrace();
                throw new SpiceException().message(e.getMessage());
            }
        }
    }
}

